package com.ecloud.gardenscenter.mqtt;

import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.common.MqttException;

/**
 * @author Squbi
 */
public class MqttClientFactory {
    private final MemoryPersistence memoryPersistence = new MemoryPersistence();
    private final String serverUrl;
    private final MqttConnectionOptions options;

    public MqttClientFactory(String serverUrl, MqttConnectionOptions options) {
        this.serverUrl = serverUrl;
        this.options = options;
    }

    /**
     * 获取mqtt客户端并连接
     *
     * @param clientId 客户端id
     * @return MqttClient
     * @author Squbi
     * @date 2021/8/19 17:48
     */
    public MqttClient getClient(String clientId) throws MqttException {
        MqttClient mqttClient = new MqttClient(serverUrl, clientId, memoryPersistence);
        mqttClient.connect(options);
        return mqttClient;
    }

    public void reConn(MqttClient client) throws MqttException {
        if (!client.isConnected()) {
            client.connect(options);
        }
    }
}
